package it.polimi.authentication.ejb.usermanagement;

import it.polimi.authentication.ejb.usermanagement.User;
import it.polimi.authentication.ejb.usermanagement.UserMgr;
import it.polimi.authentication.ejb.usermanagement.dto.UserDTO;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class UserBean
 */
@Stateless
public class UserMgrBean implements UserMgr {

	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;
	

	@Override
	public boolean save(UserDTO user) {
		User newUser = new User(user);
		
		ArrayList <User> userApp = (ArrayList <User>) em.createNamedQuery("User.findThis").setParameter("em", user.getEmail()).getResultList();
		
		if (userApp.size()== 0)
		{
			List<Group> groups = new ArrayList<Group>();
			groups.add(Group.USER);
			newUser.setGroups(groups);
			em.persist(newUser);
			return true;
		}
		else
		{
			return false;
		}
		
		
	}


	@Override
	@RolesAllowed({Group._USER,Group._ADMIN})
	public void update(UserDTO user) {
		em.merge(new User(user));
	}


	@Override
	@RolesAllowed({Group._USER,Group._ADMIN})
	public UserDTO getUserDTO() {
		UserDTO userDTO = convertToDTO(getPrincipalUser());
		return userDTO;
	}


	@Override
	@RolesAllowed({Group._USER})
	public void unregister() {
		remove(getPrincipalUser());
	}


	public User find(String email) {
    	return em.find(User.class, email);
    }
    
    public List<User> getAllUsers() {
    	return em.createNamedQuery(User.FIND_ALL, User.class)
                .getResultList();
    }

    public void remove(String email) {
		User user = find(email);
        em.remove(user);
	}
    
    public void remove(User user) {
    	em.remove(user);
	}
    
    
    public User getPrincipalUser() {
    	return find(getPrincipalEmail());
    }
	
    
    public String getPrincipalEmail() {
    	return context.getCallerPrincipal().getName();
    }

    private UserDTO convertToDTO(User user) {
		UserDTO userDTO = new UserDTO();
		userDTO.setEmail(user.getEmail());
		userDTO.setFirstName(user.getFirstName());
		userDTO.setLastName(user.getLastName());
		return userDTO;
	}


	@Override
	public UserDTO findUser(String email) {
		UserDTO appUDTO = new UserDTO();
		User appU;
		
		Query q= em.createNamedQuery("User.findThis").setParameter("em", email);
		appU = (User) q.getSingleResult();
		appUDTO.setEmail(appU.getEmail());
		appUDTO.setFirstName(appU.getFirstName());
		appUDTO.setLastName(appU.getLastName());
		appUDTO.setPassword(appU.getPassword());
		return appUDTO;
	}


	@Override
	public void updateUser(UserDTO user) {
		Query query = em.createQuery ("UPDATE User u SET u.firstName = '"+ user.getFirstName() +"' WHERE u.email = '"+ user.getEmail() +"'");
		int updateCount = query.executeUpdate();
		
		query = em.createQuery ("UPDATE User u SET u.lastName = '"+ user.getLastName() +"' WHERE u.email = '"+ user.getEmail() +"'");
		updateCount = query.executeUpdate();
		
		query = em.createQuery ("UPDATE User u SET u.password = '"+ user.getPassword() +"' WHERE u.email = '"+ user.getEmail() +"'");
		updateCount = query.executeUpdate();
		
	}
}
